<template>
  <div class="search-suggestion">
    <van-cell 
    icon="search" 
    v-for="(text, index) in suggestions" 
    :key="index" 
    @click="$emit('search',text)"
    >
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from "@/api/search";
import { debounce } from "lodash";
export default {
  data() {
    return {
      suggestions: [],
    };
  },
  props: {
    searchText: {
      type: String,
      required: true,
    },
  },
  watch: {
    searchText: {
      handler: debounce(function (value) {
        this.loadSearchSuggestion(value);
      }, 1000),
      // handler(val) {
      //   // 获取建议接口方法
      // console.log(val)
      //   this.loadSearchSuggestion(val);
      // },
      // 第一次渲染就触发
      immediate: true,
    },
  },
  methods: {
    async loadSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestions(q);
        console.log(data);
        this.suggestions = data.data.options;
      } catch (err) {
        console.log(err);
        this.$toast("数据获取失败，请稍后再试");
      }
    },
    highlight(text) {
      if(text) {
        const highlightStr=`<span class="active">${this.searchText}</span>`
        const reg=new RegExp(this.searchText,'gi')
        return text.replace(reg,highlightStr)
      }
    },
  },
};
</script>

<style lang="less" scoped>
.search-suggestion{
  /deep/ span.active{
    color: #3296fa;
  }
}
</style>